package jiuqi.controller;

import jiuqi.pojo.LoginAndRegister;
import jiuqi.service.LoginAndRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class LoginAndRegisterController {

    @Autowired
    private LoginAndRegisterService loginAndRegisterService;

    /**
     * 首页
     *
     * @return
     */
    @GetMapping("/")
    public String index() {
        return "lr/login";
    }

    @GetMapping("/toRegister")
    public String toRegister() {
        return "lr/register";
    }

    @GetMapping("/toLogin")
    public String toLogin() {
        return "lr/login";
    }

    /**
     * 登录
     *
     * @param loginAndRegister
     * @return
     */
    @RequestMapping("/loginUser")
    public String login(LoginAndRegister loginAndRegister, Map<String, Object> map) {

        if (loginAndRegisterService.login(loginAndRegister)) {
            return "redirect:/homePage";
        } else {
            map.put("msg", "用户名或者密码错误, 请重新登录");
            return "lr/login";
        }
        //return loginAndRegisterService.login(loginAndRegister)?"redirect:/homePage":"lr/loginFalse";
    }

    /**
     * 注册
     *  exitUsername 判断用户名是否存在
     * @param loginAndRegister
     * @return
     */
    @RequestMapping("/registerUser")
    public String register(LoginAndRegister loginAndRegister, Map<String, Object> map) {

        if (loginAndRegisterService.exitUsername(loginAndRegister)) {
            map.put("msg", "用户名[ "+loginAndRegister.getUsername()+" ]"+"已存在, 请重新注册");
            return "lr/register";
        } else {
            return loginAndRegisterService.register(loginAndRegister) ? "lr/login" : "redirect:/toRegister";
        }
    }
}
